<template>
  <el-dialog
    v-model="show"
    :title="title"
    destroy-on-close
  >
    <div u="flex justify-center w-full">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="110px"
        u-w-full
      >
        <el-form-item
          label="名称"
          prop="botName"
        >
          <el-input
            v-model="form.botName"
            placeholder="请输入"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          label="webhook key"
          prop="botKey"
        >
          <el-input
            v-model="form.botKey"
            placeholder="请输入"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="form.notes"
            type="textarea"
            maxlength="50"
            show-word-limit
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="cancel">
        取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="confirm"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>

const show = ref(false)
const isEdit = ref(false)
const title = computed(() => isEdit.value ? '编辑参数' : '新增参数')

const form = ref({})
const formRef = ref()

const rules = {
  botName: [{ required: true, whitespace: true, message: '请输入名称' }],
  botKey: [{ required: true, whitespace: true, message: '请输入webhook key' }]
}

const loading = ref(false)

let _cb

const add = (cb) => {
  _cb = cb
  isEdit.value = false
  form.value = {}
  show.value = true
}

const edit = (row, cb) => {
  _cb = cb
  isEdit.value = true
  form.value = cloneDeep(row)
  show.value = true
}

const cancel = () => {
  show.value = false
}

const confirm = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      loading.value = true
      try {
        await _cb(form.value)
        show.value = false
      } catch (error) {
        console.log('%c Line:97 🥛 error', 'color:#CB9C1A', error)
      }
      loading.value = false
    }
  })
}

defineExpose({
  add,
  edit
})
</script>
